package net.xfok.dict;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

public class DictEngine {
	public static final String DICT_IFO_EXT=".ifo";
	public static final String DICT_IDX_EXT=".idx";
	public static final String DICT_DZ_EXT="_dict.dz";
	public static final String DICT_YAIDX_EXT=".yaidx";
	private StarDict stardict;
	
	public DictEngine(String dictPath,String dictName){
		if(isValidDictionary(dictPath,dictName)){
			stardict = new StarDict(dictPath + dictName);
		}
	}

	public Map<String, Location> getSearchMatchList(String word) {
		if(stardict!=null){
			Map<String, Location> mp = stardict.getSearchMatchList(word);		
			if (mp != null) {
				if (SubString.isChinese(word)) {
					Iterator<String> it = mp.keySet().iterator();
					ArrayList<String> al = new ArrayList<String>();
					while (it.hasNext()) {
						String key = it.next();
						if (key.indexOf(word) == -1) {
							//mp.remove(key);
							al.add(key);
						}
					}
					for (String key: al) {
						mp.remove(key);
					}
				}
			}
			return mp;
		}
		return null;
	}
	
	public String getExplanation(Location location) {		
		if (stardict == null) {
			return "";
		}		
		return stardict.getExplanation(location);
	}
	
	public static boolean isValidDictionary(String dictPath,String dictName) {
		if (!isFileExists(dictPath + dictName + DICT_IFO_EXT)) {
			return false;
		}
		if (!isFileExists(dictPath + dictName + DICT_IDX_EXT)) {
			return false;
		}
		if (!isFileExists(dictPath + dictName + DICT_DZ_EXT)) {
			return false;
		}
		if (!isFileExists(dictPath + dictName + DICT_YAIDX_EXT)) {
			return false;
		}
		return true;
	}
	
	private static boolean isFileExists(String filename) {
		File f = new File(filename);
		return f.exists();
	}

}
